<?php
declare(strict_types=1);
namespace app\service;

class Encryptor {
    private static $publicKey;
    private static $privateKey;
    /**
     * 初始化
     */
    public static function init()
    {
        self::$publicKey = config('rsa.public_key');
        self::$privateKey = config('rsa.private_key');
    }

    /**
     * 加密
     * @param $data
     * @return bool|string
     */
    public static function encrypt($data)
    {
        try {
            self::init();
            $puKey = openssl_pkey_get_public(self::$publicKey);
            $encrypted ='';
            openssl_public_encrypt($data,$encrypted,$puKey);
            return $encrypted;
        } catch (\Exception $e) {
            return error('加密失败');
        }          
    }

    /**
     * 解密
     * @param $data
     * @return bool|string
     */
    public static function decrypt($data)
    {
        try {
            self::init();
            $base64 = base64_decode($data);
            $prKey = openssl_pkey_get_private(self::$privateKey);
            $decryptedData = '';
            openssl_private_decrypt($base64,$decryptedData,$prKey);
            return $decryptedData;
        } catch (\Exception $e) {
            return error('解密失败');
        }       
    }
}
